package ru.urfc.portal.rest;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.urfc.portal.dao.filter.Filter;
import ru.urfc.portal.dao.filter.Operator;
import ru.urfc.portal.exceptions.InternalException;
import ru.urfc.portal.ui.client.Constants;
import ru.urfc.portal.ui.client.Utils;

public class BaseService implements Constants {

	protected void redirect(HttpServletResponse response, String restUrl, String fileName) {
		try {
			fileName = fileName.replace("/", "-");
			response.sendRedirect(restUrl + "/" + URLEncoder.encode(fileName, "UTF-8").replace("+", " "));
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	protected String joinPath(Object... path) {
		StringBuilder result = new StringBuilder();
		for (Object item: path) {
			if (result.length() != 0) {
				result.append("/");
			}
			result.append(item.toString());
		}
		return result.toString();
	}
	
	public static final DateFormat DATE_FORMATTER = new SimpleDateFormat(Utils.DATE_FORMAT);
	
	public static class ParseDateException extends InternalException {
		public ParseDateException(Throwable cause, String message) {
			super(cause, message);
		}
	}

	public static class UrlDecodeException extends InternalException {
		public UrlDecodeException(Throwable cause, String message) {
			super(cause, message);
		}
	}

	protected Date getDate(String parameter, HttpServletRequest request) {
		try {
			String value = getStr(parameter, request);
			return value == null? null: DATE_FORMATTER.parse(value);
		} catch (ParseException e) {
			throw new ParseDateException(e, "Invalid filter parameter");
		}
	}
	
	protected Long getLong(String parameter, HttpServletRequest request) {
		String value = getStr(parameter, request);
		return value == null? null: Long.valueOf(value);		
	}
	
	protected String getStr(String parameter, HttpServletRequest request) {
		try {
			request.setCharacterEncoding("UTF-8");
			return request.getParameter(parameter);
		} catch (UnsupportedEncodingException e) {
			throw new UrlDecodeException(e, "Can't decode to UTF-8");
		}
	}

	protected Filter addFilterFromToDates(Filter filter, HttpServletRequest request) {
		filter.add("date", Operator.GREAT_OR_EQUAL, getDate(FILTER_FROM_DATE, request));
		filter.add("date", Operator.LESS_OR_EQUAL, getDate(FILTER_TO_DATE, request));
		return filter;
	}

}
